package com.nash.demands;

import java.io.PrintWriter;
import java.io.StringWriter;

import org.ksoap2.SoapFault;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.util.Log;

public class DemandsException extends Exception {
  /**
   * 
   */
  private static final long serialVersionUID = 8644953444646852739L;
  public final static int SOAP_FAULT=1;
  public final static int SOAP_FAULT_LIC_NOT_FOUND=1;
  public final static int SOAP_FAULT_LIC_BAD=2;
  public final static int SOAP_FAULT_LIC_ALREADY_USED=3;
  public final static int SOAP_FAULT_LIC_USER_NOT_DEFINED=4;
  public final static int SOAP_FAULT_LIC_USER_INVALID=5;

  public final static int EX_OPTIONS=2;
  public final static int EX_OPTIONS_NO_FOUND=1;

  public final static int EX_NETWORK=3;

  public final static int EX_HALT=1000;

  private int code;
  private int code2;
  public DemandsException(final int c,final int c2){
    code=c;
    code2=c2;
  }
  public DemandsException(Exception e){
    //e.getClass()
    super(e);
    if (SoapFault.class.isInstance(e)){
      code=SOAP_FAULT;
      if (((SoapFault)e).faultstring.equals("License: not found")){
        code2=SOAP_FAULT_LIC_NOT_FOUND;
      }
      else if (((SoapFault)e).faultstring.equals("License: bad")){
        code2=SOAP_FAULT_LIC_BAD;
      }
      else if (((SoapFault)e).faultstring.equals("License: already used")){
        code2=SOAP_FAULT_LIC_ALREADY_USED;
      }
      else if (((SoapFault)e).faultstring.equals("License: user not defined")){
        code2=SOAP_FAULT_LIC_USER_NOT_DEFINED;
      }
      else if (((SoapFault)e).faultstring.equals("License: invalid user")){
        code2=SOAP_FAULT_LIC_USER_INVALID;
      }
    }
    else if (java.net.UnknownHostException.class.isInstance(e)){
      code=EX_NETWORK;
    }
    else
      code=0;
  };
  public int getCode(){
    return code;
  }
  public int getCode2(){
    return code2;
  }
  
  public static void dialogError(final Activity context, Exception e, final boolean finish){
    
    StringWriter writerStr = new StringWriter();
    PrintWriter myPrinter = new PrintWriter(writerStr);
    e.printStackTrace(myPrinter);
    String stackTraceStr = writerStr.toString();
    //writerStr.getBuffer();
    Log.e("shit", stackTraceStr);      
    
    AlertDialog alertDialog = new AlertDialog.Builder(context).create();
    alertDialog.setTitle("Ошибка");
    alertDialog.setMessage(e.toString());
    alertDialog.setButton("Ok", new DialogInterface.OnClickListener() {
      public void onClick(DialogInterface dialog, int whichButton) {
        dialog.dismiss();
        if (finish)
          context.finish();
      }
    });
    alertDialog.show();
    
  }
}
